<template>
    <div class="login">
      <h2>登录</h2>
      <form @submit.prevent="login">
        <div>
          <label for="username">用户名</label>
          <input v-model="username" type="text" id="username" required>
        </div>
        <div>
          <label for="password">密码</label>
          <input v-model="password" type="password" id="password" required>
        </div>
        <button type="submit">登录</button>
      </form>
      <div v-if="error">{{ error }}</div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        username: '',
        password: '',
        error: null
      };
    },
    methods: {
      async login() {
        try {
          const response = await axios.post('http://localhost:5000/login', {
            username: this.username,
            password: this.password
          });
          // 将JWT token存储在本地存储中
          localStorage.setItem('token', response.data.access_token);
          this.$router.push('/protected');  // 登录成功后跳转到受保护的页面
        } catch (err) {
          this.error = err.response.data.msg || '登录失败';
        }
      }
    }
  }
  </script>
  
  <style scoped>
  /* 添加样式 */
  </style>
  